package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.entity.TaskEntity;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
@Topic(TopicConfig.VMS_STATUS_TOPIC)
public class VMStatusHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;


    /**
     * 接收到售货机坏的消息后，自动创建维修工单
     * @param jsonMsg
     * @throws IOException
     */
    @Override
    public void process(String jsonMsg) throws IOException {
        //1.解析参数
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
            //非空判断
        if(vmStatusContract==null||vmStatusContract.getStatusInfo()==null||
        vmStatusContract.getStatusInfo().size()<=0){
            return;
        }
            //任何一个部件坏了就满足条件，自动下发维修工单
        if(vmStatusContract.getStatusInfo().stream().anyMatch(s->s.isStatus()==false)){
            try {
                //根据售货机编号，查询售货机
                VmVO vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());
                if(vmInfo==null){
                    return;
                }
                //获取今日工单最少的用户的id
                int userId = taskService.getLeastUser(vmInfo.getRegionId(), true);
                //获取的方法里如果获取的是null，返回的结果是0；
                if(userId!=0){
                    TaskViewModel task=new TaskViewModel();
                    task.setUserId(userId);//执行人
                    task.setInnerCode(vmStatusContract.getInnerCode());//售货机编码
                    task.setProductType(VMSystem.TASK_TYPE_REPAIR );//维修工单 类型
                    task.setCreateType(0);//自动工单
                    task.setDesc(jsonMsg);//将报文进行存储
                    task.setAssignorId(0);//自动工单
                    taskService.addTask(task);
                }
            } catch (Exception e) {
                log.error("创建自动维修工单失败，msg is:"+jsonMsg);
            }
        }
    }
}
